<template>
  <div class="role">
    <a-card :bordered="false">
      <!-- 表格顶部搜索部分 -->
      <c-table-search-form
        v-model="tableSearchForm"
        :datas="tableSearchFormData"
        @onSearch="onSearch"
        @onAdd="onAdd('', 'add')"
      >
        <template slot="startPermissionBtn">
          <a-popconfirm
            :title="`是否启动权限？`"
            ok-text="确定"
            cancel-text="取消"
            @confirm="onStartPermissions"
          >
            <a-button class="bgGreen" icon="play-circle">启动权限</a-button>
          </a-popconfirm>
        </template>
        <template slot="allDeleteBtn">
          <a-popconfirm
            :title="`是否确认删除所勾选的权限?`"
            v-if="selectedRowKeys.length > 0"
            ok-text="确定"
            cancel-text="取消"
            @confirm="onDeleteAll"
          >
            <a-button icon="delete" type="danger">批量删除</a-button>
          </a-popconfirm>
        </template>
      </c-table-search-form>

      <!-- 表格部分 -->
      <c-table
        :scroll="{ x: 1500 }"
        rowSelection
        :columns="columns"
        :datas="tableData"
        :loading="loading"
        @onSelectChange="onSelectChange"
      >
        <!-- 表格自定义内容 -->
        <template slot="type" slot-scope="type">
          <a-tag :color="type.tableRow === 1 ? 'green' : 'blue'">
            {{
              type.tableRow === 0 || type.tableRow === "0"
                ? "菜单"
                : type.tableRow === 1 || type.tableRow === "1"
                ? "按钮"
                : type.tableRow === 2 || type.tableRow === "2"
                ? "平台菜单"
                : ""
            }}
          </a-tag>
        </template>
        <template slot="resourceState" slot-scope="resourceState">
          <a-tag :color="resourceState.tableRow === 0 ? 'red' : 'blue'">
            {{
              resourceState.tableRow === 0
                ? "未生效"
                : resourceState.tableRow === 1
                ? "已生效"
                : ""
            }}
          </a-tag>
        </template>
        <template slot="createDate" slot-scope="row">
          <span>{{ moment(row.tableRow).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
        <template slot="icon" slot-scope="icon">
          <p>
            <Icon
              class="table-list-icon"
              :iconStyle="iconStyle"
              :type="icon.tableRow"
            />
          </p>
        </template>

        <!-- 表格操作按钮 -->
        <template slot="handle" slot-scope="row">
          <a-popconfirm
            :title="
              `是否${
                row.tableRow.resourceState === 0 ? '启动' : '停止'
              }该权限资?`
            "
            ok-text="确定"
            cancel-text="取消"
            @confirm="
              onStartStatus(row.tableRow.id, row.tableRow.resourceState)
            "
          >
            <a
              @click.stop=""
              :class="row.tableRow.resourceState === 0 ? '' : 'textGrey'"
            >
              <Icon
                v-if="row.tableRow.resourceState === 0"
                :iconStyle="startIconStyle"
                :type="'zk-back-start'"
              />
              <a-icon v-else type="stop" />
              {{ row.tableRow.resourceState === 0 ? "启动" : "停止" }}
            </a>
          </a-popconfirm>
          <a-divider type="vertical" />
          <a @click.stop="onEdit(row.tableRow)"> <a-icon type="edit" />编辑 </a>
          <a-divider type="vertical" />
          <a-popconfirm
            :title="`是否确认删除该权限资源管理?`"
            ok-text="确定"
            cancel-text="取消"
            @confirm="onDel([row.tableRow.id])"
          >
            <a @click.stop=""> <a-icon type="delete" />删除 </a>
          </a-popconfirm>
        </template>
      </c-table>
      <a-drawer
        :title="handleType == 'add' ? '新增权限资源' : '编辑权限资源'"
        :width="'30%'"
        :visible="visible"
        @ok="onOk"
        @cancel="onCancel"
        :destroyOnClose="true"
        @close="onCancel"
      >
        <c-form-model
          class="margin-b70"
          :datas="formData"
          v-model="form"
          :rules="rules"
          ref="formModels"
        >
          <!-- formModel自定义部分 -->
          <a-input
            slot="icon"
            allow-clear
            v-model="form.icon"
            placeholder="请输入菜单图标"
            @click="openMenuIconSelector"
          ></a-input>
          <a-radio-group
            slot="type"
            slot-scope="row"
            v-model="form[row.tableRow.prop]"
          >
            <a-radio value="0">菜单</a-radio>
            <a-radio value="1">按钮</a-radio>
            <a-radio value="2">工作台菜单</a-radio>
          </a-radio-group>

          <a-switch
            slot="hidden"
            size="small"
            v-model="form.hidden"
            default-checked
          />
        </c-form-model>
        <div class="drawer-footer-btn flex-center">
          <a-button class="margin-r10" @click="onCancel">取消</a-button>
          <a-button type="primary" :loading="confirmLoading" @click="onOk"
            >确定</a-button
          >
        </div>
      </a-drawer>

      <a-modal
        width="35%"
        v-model="menuIconVisible"
        :zIndex="zIndex"
        :footer="null"
        title="请选择菜单图标"
      >
        <icon-selector
          v-model="currentSelectedIcon"
          @change="onIconChange"
        ></icon-selector>
      </a-modal>
    </a-card>
  </div>
</template>
<script>
import {
  getResourceList,
  deleteResourceList,
  addResourceList,
  updateResourceList,
  refreshAuthdata,
  updateBaseresource
} from "@/api/mallSystem/permissionResource";
import { refactoringArr, findChildIdArr } from "@/util/common";
import IconSelector from "@/components/IconSelector";
const moment = require("moment");

const columns = [
  {
    title: "菜单名称",
    dataIndex: "resourceName",
    key: "resourceName",
    align: "center",
    className: "text-left",
    fixed: "left",
    width: 220
  },
  {
    title: "前端标识",
    dataIndex: "flag",
    key: "flag",
    align: "center",
     width: 180
  },
  {
    title: "菜单类型",
    dataIndex: "type",
    key: "type",
    scopedSlots: { customRender: "type" },
    align: "center",
    width: 180
  },
  {
    title: "菜单状态",
    dataIndex: "resourceState",
    key: "resourceState",
    scopedSlots: { customRender: "resourceState" },
    align: "center",
    width: 150
  },
  {
    title: "资源URL",
    dataIndex: "url",
    key: "url",
    align: "center"
  },
  {
    title: "菜单图标",
    dataIndex: "icon",
    key: "icon",
    scopedSlots: { customRender: "icon" },
    align: "center",
    width: 120
  },
  {
    title: "创建时间",
    dataIndex: "createDate",
    key: "createDate",
    scopedSlots: { customRender: "createDate" },
    align: "center",
    width: 180
  },
  {
    title: "操作",
    key: "handle",
    scopedSlots: { customRender: "handle" },
    width: 200,
    align: "center",
    fixed: "right"
  }
];
const rules = {
  resourceName: [
    { required: true, message: "请输入权限名称", trigger: "change" }
  ],
  flag: [{ required: true, message: "请输入前端标识", trigger: "change" }],
  orderNum: [{ required: true, message: "请输入排序", trigger: "change" }],
  type: [{ required: true, message: "请输入类型", trigger: "blur" }],
  moduleUrl: [{ required: true, message: "请输入组件URL", trigger: "blur" }],
  path: [{ required: true, message: "请输入前端URL", trigger: "blur" }]
};
export default {
  name: "permissionResource",
  components: {
    IconSelector
  },
  data() {
    return {
      columns,
      rules,
      higherMenu:[],
      iconStyle: {
        fontSize: "18px"
      },
      startIconStyle: {
        fontSize: "14px",
        color: "#758cff"
      },
      tableSearchForm: {
        searchKey: ""
      },
      tableSearchFormData: [
        {
          label: "请输入菜单名称",
          prop: "searchKey",
          type: "search"
        },
        {
          prop: "addBtn",
          type: "addBtn"
        },
        {
          prop: "startPermissionBtn",
          type: "slot"
        },
        {
          prop: "allDeleteBtn",
          type: "slot"
        }
      ],
      zIndex: 2000,
      currentSelectedIcon: "",
      handleType: "add",
      loading: false,
      tableData: [],
      deleteIdArr: [],
      selectedRowKeys: [],
      selectedRows: [],
      visible: false,
      menuIconVisible: false,
      confirmLoading: false,
      form: {
        resourceDirection: 0,
        parentId: "",
        flag: "",
        id: "",
        orderNum: "",
        resourceName: "",
        type: "0",
        url: "",
        moduleUrl: "",
        redirect: "",
        affiliation: "",
        icon: "",
        path: "",
        hidden: true
      }
    };
  },  
  created() {
    this.onPageOnlod();
  },
  computed: {
    formData() {
      let res = [
        {
          label: "上级菜单",
          prop: "parentId",
          type: "tree-select",
          typeData: this. higherMenu
        },
        {
          label: "菜单名称",
          prop: "resourceName"
        },
        {
          label: "菜单类型",
          prop: "type",
          type: "slot"
        },
        {
          label: "前端标识",
          prop: "flag"
        },
        {
          label: "方向标识",
          prop: "resourceDirection",
          type: "select",
          typeData: [
            {
              label: "公共",
              value: 0
            },
            {
              label: "采购",
              value: 1
            },
            {
              label: "销售",
              value: 2
            },
            {
              label: "采购与销售",
              value: 3
            }
          ]
        },
        {
          label: "资源URL",
          prop: "url",
          placeholder: "请输入资源URL（后台没有对应请求资源则默认为空）"
        },
        {
          label: "组件URL",
          prop: "moduleUrl",
          hidden: this.form.type=== '1' ? true : false
        },
        {
          label: "前端URL",
          prop: "path",
          hidden: this.form.type === '1' ? true : false
        },
        {
          label: "重定向URL",
          prop: "redirect",
          hidden: this.form.type === '1' ? true : false
        },
        {
          label: "所属菜单",
          prop: "affiliation",
          hidden: this.form.type === '1' ? true : false
        },
        {
          label: "图标",
          prop: "icon",
          type: "slot"
        },
        {
          label: "排序",
          prop: "orderNum",
          type: "number"
        },
        {
          label: "显隐",
          prop: "hidden",
          type: "slot"
        },
        {
          label: "备注",
          prop: "remark",
          type: "textarea"
        }
      ];
      return res;
    }
  },
   watch: {
  },
  methods: {
    moment,
    refactoringArr,
    findChildIdArr,
    onIconChange(icon) {
      this.form.icon = icon;
      this.menuIconVisible = false;
    },
    openMenuIconSelector() {
      this.menuIconVisible = true;
    },
    operationAddDisabled(list, id, disabled, status) {
      const res = [];
      for (let i = 0; i < list.length; i++) {
        const baseItem = list[i];
        baseItem[disabled] = false;
        res.push(baseItem);
        if (baseItem.children) {
          findChild(baseItem.children);
        }
        if (id && baseItem["id"] == id) {
          baseItem[disabled] = status;
          if (baseItem.children) {
            findChild(baseItem.children, "match");
          }
        }
      }
      function findChild(item, match) {
        for (let y = 0; y < item.length; y++) {
          item[y][disabled] = false;
          if (match || (id && item[y]["id"] == id)) {
            item[y][disabled] = status;
            if (item[y].children) {
              findChild(item[y].children, "match");
            }
          } else {
            if (item[y].children) {
              findChild(item[y].children);
            }
          }
          res.push(item);
        }
      }
      return list;
    },

    onSearch() {
      this.onPageOnlod();
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    onPageOnlod() {
      this.loading = true;
      getResourceList({
        resourceName: this.tableSearchForm.searchKey.trim()
      }).then(res => {
        if (!res.data) res.data = [];
        if (!this.tableSearchForm.searchKey) {
         this.higherMenu = refactoringArr(
            res.data,
            item => {
              return {
                id: item.id,
                key: item.id,
                parentId: item.parentId,
                value: item.id,
                title: item.resourceName,
                type: item.type
              };
            },
            0
          );
        }
        this.tableData = refactoringArr(res.data, "", 0);
        // console.log(this.tableData)
        this.loading = false;
      });
    },
    onAdd() {
      this.form = {
        resourceDirection: 0,
        parentId: "",
        flag: "",
        id: "",
        orderNum: "",
        resourceName: "",
        type: "0",
        url: "",
        moduleUrl: "",
        redirect: "",
        affiliation: "",
        icon: "",
        path: "",
        hidden: true
      };
      this.operationAddDisabled(this.formData[0].typeData, "", "disabled");
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.handleType = "add";
      
      this.visible = true;
    },
    onOk() {
      const that = this;
      let onFun;
      that.handleType === "add"
        ? (onFun = addResourceList)
        : (onFun = updateResourceList);
      this.$refs.formModels.handleValidate().then(data => {
        that.confirmLoading = true;
        if (data.parentId == "") data = { ...data, parentId: "0" };
        data.hidden
          ? (data = { ...data, hidden: 0 })
          : (data = { ...data, hidden: 1 });
        onFun(data)
          .then(res => {
            that.$message.success("操作成功");
            that.onPageOnlod();
            that.selectedRowKeys = [];
            that.selectedRows = [];
            that.confirmLoading = false;
            that.visible = false;
          })
          .catch(() => {
            this.confirmLoading = false;
          });
      });
    },
    onCancel(row) {
      this.visible = false;
    },
    onDel(idArr, type) {
      let result = [];
      idArr.map(itemId => {
        result.push(...findChildIdArr(this.tableData, itemId));
      });
      deleteResourceList(result).then(res => {
        this.$message.success("操作成功");
        this.selectedRowKeys = [];
        this.selectedRows = [];
        this.onPageOnlod();
      });
    },
    onEdit(row) {
      this.operationAddDisabled(
        this.formData[0].typeData,
        row.id,
        "disabled",
        true
      );
      this.form = JSON.parse(JSON.stringify(row));
      this.form["type"] = row.type + "";
      row.parentId === 0 ? (this.form["parentId"] = "") : this.form["parentId"];
      row.hidden === 0 || row.hidden === "0"
        ? (this.form["hidden"] = true)
        : (this.form["hidden"] = false);
      this.handleType = "edit";
      this.visible = true;
    },
    onDeleteAll() {
      this.deleteIdArr = [];
      this.selectedRows.map(item => {
        return this.deleteIdArr.push(item.id);
      });
      this.onDel([...new Set(this.deleteIdArr)], "all");
    },
    //开启权限资源
    onStartPermissions() {
      refreshAuthdata().then(() => {
        this.$message.success("启动成功");
        this.onPageOnlod();
      });
    },
    //开启权限资源（表格内操作）
    onStartStatus(id, status) {
      let result = [];
      result.push(...findChildIdArr(this.tableData, id)); 
      updateBaseresource({
        ids: result,
        resourceState: status == 0 ? 1 : 0
      }).then(() => {
        this.$message.success("操作成功");
        this.onPageOnlod();
      });
    }
  }
};
</script>
<style lang="less" scoped>
::v-deep td.text-left {
  text-align: left !important;
}

::v-deep.ant-table td {
  white-space: nowrap;
}
</style>
